<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { SearchStuModel, StuModel, StuModelArray, DeptModelArray, LoginInfo, ClazzModelArray } from '@/api/model/model'
import axios from 'axios'
import { queryStuList, addStu, getStuById, updateStu, deleteStuByIds, putViolation } from '@/api/stu/index'
import { queryClazzList, queryClazzLists } from '@/api/clazz/index'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取token
import { useLoginEmpStore } from '@/stores/loginEmp'
const loginEmpStore = useLoginEmpStore();
const loginInfo = ref<LoginInfo>(loginEmpStore.getLoginInfo());

// 页面顶部的搜索
const searchForm = ref<SearchStuModel>({
    name: '',
    degree: '',
    clazzId: ''
})

onMounted(() => {
    query();
    queryClazzs();
   
});

const query = async () => {

    const res = await queryStuList(searchForm.value.name, searchForm.value.degree, searchForm.value.clazzId, currentPage.value, pageSize.value);
    stuList.value = res.data.rows
    total.value = res.data.total
}

const queryClazzs = async () => {
    const res = await queryClazzLists();
    clazzList.value = res.data;
}


const clear = () => {
    searchForm.value = { name: '', degree: '', clazzId: '' }
}


// 页面主体的数据列表
const stuList = ref<StuModelArray>();
// 分页的数据
let currentPage = ref<number>(1)
const pageSize = ref<number>(5);
const total = ref<number>(0);
const handleSizeChange = () => {
    currentPage = ref<number>(1);
    query();
}
const handleCurrentChange = () => {
    query();
}
// dialog弹框
const dialogFormVisible = ref<boolean>(false)
const clazzList = ref<ClazzModelArray>()
const dialogTitle = ref<string>('')
const insertOrUpdateForm = ref<StuModel>({
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: '',
    clazzName: ''
});
const formLabelWidth = "80px";
// 新增
const openAddDialog = () => {
    dialogFormVisible.value = true;
    dialogTitle.value = "新增学员";
}



// violation弹框
const violationFormVisible = ref<boolean>(false)
const violationFormRef = ref()
const violationForm = ref({
    id: '',
    score: '',
});


//违纪
const handleViolation = async (idx: number, row: StuModel) => {
    if (!row.id) {
        return;
    }

    violationFormVisible.value = true;
    violationForm.value.id = row.id;
}


const violation = async (violationFormRef: { value: string }) => {
    await putViolation(violationForm.value.id, violationForm.value.score);
    violationFormVisible.value = false;
    query();

}


// 更新
const handleEdit = async (idx: number, row: StuModel) => {
    if (!row.id) {
        return;
    }
    // 展示弹框
    dialogFormVisible.value = true;
    dialogTitle.value = "修改学员";
    // 回显查询，参数是id
    const res = await getStuById(row.id);
    insertOrUpdateForm.value = res.data;
    // 数据类型不一致导致select无法选中
    insertOrUpdateForm.value.gender = '' + insertOrUpdateForm.value.gender
    console.log(insertOrUpdateForm.value.degree);
}

const insertOrUpdate = (formEL: FormInstance | undefined) => {
    if (!formEL) {
        return;
    }
    // 先校验表单的格式
    formEL.validate(async (valid) => {
        if (valid) {
            // 校验通过
            let res = null;
            let insertFlag = null;
            if (insertOrUpdateForm.value.id) {//修改
                insertFlag = false;
                res = await updateStu(insertOrUpdateForm.value);
            } else {// 新增
                insertFlag = true;
                res = await addStu(insertOrUpdateForm.value);
            }
            if (!res.code) {
                ElMessage.error(res.msg);
            } else {
                // 隐藏dialog
                dialogFormVisible.value = false;
                // 清空dialog，通过dialog的回调统一处理
                ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
                query();
            }
        }
    });

}

const handleDelete = (idx: number, row: StuModel) => {
    ElMessageBox.confirm('您确认删除此数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            const res = await deleteStuByIds('' + row.id);
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg, })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();
            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}
// 保存所有选中的行的id
const selectIds = ref<(number | undefined)[]>([])
// 入参：是所有的选中的行的数据的数组
const handleSelectionChange = (rows: StuModelArray) => {
    // 重置selectIds
    selectIds.value = []
    if (!selectIds) {
        return;
    }
    if (!rows || rows.length <= 0) {
        selectIds.value = []
    } else {
        for (let i = 0; i < rows.length; i++) {
            selectIds.value.push(rows[i].id);
        }

    }
}
const batchDelete = () => {
    // 先判断seleectIds是否有值
    if (!selectIds.value || selectIds.value.length <= 0) {
        ElMessage({ type: 'error', message: '没有选中任何数据' })
        return;
    }
    ElMessageBox.confirm('您确认删除这些数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            // 数组元素拼接：selectIds.value.join(",")
            const res = await deleteStuByIds(selectIds.value.join(","));
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg, })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();

            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}


// 表单校验
const rules = ref<FormRules<StuModel>>({
    name: [
        { required: true, message: '姓名名不能为空', trigger: 'blur' },
    ],
    no: [
        { required: true, message: '学号不能为空', trigger: 'blur' },
        { pattern: /^\d{10}$/, message: '学号必须是10位的数字', trigger: 'blur' },
    ],
    gender: [
        { required: true, message: '性别不能为空', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3-9][0-9]{9}$/, message: '手机号格式有误', trigger: 'blur' },
    ],
    idCard: [
        { pattern: /^(\d{6})(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}(\d|X)$/, message: '身份证格式有误', trigger: 'blur' },
    ],
})
const dialogFromRef = ref<FormInstance>();



// dialog关闭的时候自动回调
function dialogClose() {
    if (!dialogFromRef || !dialogFromRef.value) {
        return;
    }
    insertOrUpdateForm.value =
    {
        name: '',
        no: '',
        gender: '',
        phone: '',
        idCard: '',
        isCollege: '',
        address: '',
        degree: '',
        graduationDate: '',
        clazzId: '',
        clazzName: ''
    }
    // 重置form校验规则
    dialogFromRef.value.resetFields();
}


function violationClose() {
    if (!violationForm || !violationForm.value) {
        return;
    }
    violationForm.value = {
        id: '',
        score: '',
    }

}


const isCollegeList = [{ id: 1, name: "是" },{ id: 2, name: "否" }, ]
 
const degreeList = [{ id: 1, name: "初中" },{ id: 2, name: "高中" },{ id: 3, name: "大专" },{ id: 4, name: "本科" },{ id: 5, name: "硕士" },{ id: 6, name: "博士" }, ]
</script>
<template>
    <span class="title">学员管理 </span>

    <!----------------------------------搜索框-------------------------------------->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入学生姓名" style="width:200px" clearable />
        </el-form-item>
        <el-form-item label="最高学历">
            <el-select v-model="searchForm.degree" placeholder="请选择" style="width:200px" clearable>
                <el-option label="初中" value="1" />
                <el-option label="高中" value="2" />
                <el-option label="大专" value="3" />
                <el-option label="本科" value="4" />
                <el-option label="硕士" value="5" />
                <el-option label="博士" value="6" />
            </el-select>
        </el-form-item>
        <el-form-item label="所属班级" :label-width="formLabelWidth">
            <el-select v-model="searchForm.clazzId" placeholder="请选择" style="width:200px" clearable>
                <el-option :label="clazz.name" :value="clazz.id" v-for="(clazz, index) in clazzList" :key="clazz.id" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
    </el-form>

    <el-button type="success" @click="openAddDialog">+ 新增学员</el-button>
    <el-button type="danger" @click="batchDelete">- 批量删除</el-button>

    <!-----------------------页面主体的数据列表-------------------------------->
    <el-table :data="stuList" border style="width: 100%; margin-top:10px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column prop="no" label="学号" width="130" align="center" />
        <el-table-column prop="clazzName" label="班级" width="150" align="center" />
        <el-table-column prop="gender" label="性别" width="60" align="center">
            <template #default="scope">
                <span v-if="scope.row.gender == 1">男</span>
                <span v-else-if="scope.row.gender == 2">女</span>
                <span v-else>其他</span>
            </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机号" width="150" align="center" />
        <el-table-column prop="degree" label="最高学历" width="100" align="center">
            <template #default="scope">
                <span v-if="scope.row.gender == 1">初中</span>
                <span v-else-if="scope.row.degree == 2">高中</span>
                <span v-else-if="scope.row.degree == 3">大专</span>
                <span v-else-if="scope.row.degree == 4">本科</span>
                <span v-else-if="scope.row.degree == 5">硕士</span>
                <span v-else-if="scope.row.degree == 6">博士</span>
                <span v-else>其他</span>
            </template>
        </el-table-column>
        <el-table-column prop="violationCount" label="违纪次数" width="130" align="center" />
        <el-table-column prop="violationScore" label="违纪扣分" width="130" align="center" />
        <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
        <el-table-column label="操作" align="center">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>
                <el-button size="small" type="warning" @click="handleViolation(scope.$index, scope.row)">
                    违纪
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!----------------------------------分页组件---------------------------------------->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top:10px" />
    <!----------------------------------dialog弹框-------------------------------------->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="700" @close="dialogClose">
        <el-form :model="insertOrUpdateForm" ref="dialogFromRef" :rules="rules">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="insertOrUpdateForm.name" autocomplete="off" placeholder="请输入姓名" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="学号" :label-width="formLabelWidth" class="required-label" prop="no">
                        <el-input v-model="insertOrUpdateForm.no" autocomplete="off" placeholder="请输入学号" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="formLabelWidth" required prop="gender">
                        <el-select v-model="insertOrUpdateForm.gender" placeholder="请选择" clearable style="width: 100%">
                            <el-option label="男" value="1" />
                            <el-option label="女" value="2" />
                            <el-option label="其他" value="3" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号" :label-width="formLabelWidth" class="required-label" prop="phone">
                        <el-input v-model="insertOrUpdateForm.phone" autocomplete="off" placeholder="请输入手机号"
                            clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="身份证号" :label-width="formLabelWidth" prop="idCard">
                        <el-input v-model="insertOrUpdateForm.idCard" autocomplete="off" placeholder="请输入身份证号"
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否院校" :label-width="formLabelWidth" >
                        <el-select v-model="insertOrUpdateForm.isCollege" placeholder="请选择" clearable
                            style="width: 100%">
                            <el-option :label="isCollege.name" :value="isCollege.id" v-for="(isCollege, index) in isCollegeList" :key="isCollege.id"/>
                          
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="联系地址" :label-width="formLabelWidth" prop="address">
                        <el-input v-model="insertOrUpdateForm.address" autocomplete="off" placeholder="请输入联系地址"
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="最高学历" :label-width="formLabelWidth" class="required-label" prop="degree">
                        <el-select v-model="insertOrUpdateForm.degree" placeholder="请选择" style="width:100%">
                            <el-option :label="degree.name" :value="degree.id" v-for="(degree, index) in degreeList" :key="degree.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>

                <el-col :span="12">
                    <el-form-item label="毕业时间" :label-width="formLabelWidth" style="width:100%">
                        <el-date-picker style="width:100%" v-model="insertOrUpdateForm.graduationDate" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择毕业时间" />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="所属班级" :label-width="formLabelWidth">
                        <el-select v-model="insertOrUpdateForm.clazzId" placeholder="请选择" style="width: 100%">
                            <el-option :label="clazz.name" :value="clazz.id" v-for="(clazz, index) in clazzList"
                                :key="clazz.id" />
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="insertOrUpdate(dialogFromRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- violation  提示框 -->
    <el-dialog v-model="violationFormVisible" title="提示" width="500" @close="violationClose">
        <el-form :model="violationForm" ref="violationFormRef">
            <el-row>
                <el-form-item label="请输入违纪扣分" />
            </el-row>
            <el-row>
                <el-col>
                    <el-input v-model="violationForm.score" style="width: 100%" autocomplete="off" clearable />
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="violationFormVisible = false">取消</el-button>
                <el-button type="primary" @click="violation(violationFormRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>



</template>

<style scope>
.title {
    font-size: 20px;
    font-weight: 600;
}

.demo-form-inline {
    margin-top: 10px
}

.required-label .el-form-item__label:before {
    content: '*';
    color: red;
    margin-right: 2px;
}

.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>